#
# This file is a part of the open-eBackup project.
# This Source Code Form is subject to the terms of the Mozilla Public License, v. 2.0.
# If a copy of the MPL was not distributed with this file, You can obtain one at
# http://mozilla.org/MPL/2.0/.
#
# Copyright (c) [2024] Huawei Technologies Co.,Ltd.
#
# THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
# EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
# MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
#

from common.common import get_local_ips
from common.exception.common_exception import ErrCodeException
from common.job_const import JobNameConst, ParamKeyConst
from common.parse_parafile import get_env_variable
from gaussdbt.single import LOGGER
from gaussdbt.single.comm.gst_single_const import GstSingleKeyConst
from gaussdbt.single.comm.gst_single_error_code import ErrorCode


class GstSingleParamUtil:
    @staticmethod
    def get_job_id(param_dict):
        """
        获取任务ID
        :param param_dict: 任务参数
        :return: 任务ID
        """
        return param_dict.get(ParamKeyConst.JOB, {}).get(ParamKeyConst.JOB_ID, "")

    @staticmethod
    def get_sub_job_id(param_dict):
        """
        获取子任务ID
        :param param_dict: 任务参数
        :return: 子任务ID
        """
        return param_dict.get(ParamKeyConst.SUB_JOB, {}).get(ParamKeyConst.SUB_JOB_ID, "")

    @staticmethod
    def get_node_ip(param_dict):
        """
        获取本机上报的IP
        :param param_dict: 任务参数
        :return: 本机上报的IP
        """
        all_node_infos = param_dict.get(ParamKeyConst.JOB, {}).get(ParamKeyConst.TARGET_ENV, {}) \
            .get(ParamKeyConst.NODES, [])
        all_node_ips = [i.get(ParamKeyConst.ENDPOINT) for i in all_node_infos]
        local_ip_list = get_local_ips()
        inter_sec_ips = list(set(all_node_ips).intersection(set(local_ip_list)))
        return inter_sec_ips[0] if inter_sec_ips else ""

    @staticmethod
    def get_os_user(task_name, pid, is_restore=False):
        """获取资源的操作系统用户名"""
        if task_name == JobNameConst.QUERY_PERMISSION:
            os_user_key = GstSingleKeyConst.APP_AUTH_AUTHKEY + "_" + pid
        else:
            if is_restore:
                os_user_key = GstSingleKeyConst.JOB_TARGETOBJ_AUTH_AUTHKEY + "_" + pid
            else:
                os_user_key = GstSingleKeyConst.JOB_PROTECTOBJ_AUTH_AUTHKEY + "_" + pid
        return get_env_variable(os_user_key)

    @staticmethod
    def get_backup_type(param_dict):
        """获取备份类型"""
        return param_dict.get(ParamKeyConst.JOB, {}).get(ParamKeyConst.JOB_PARAM, {}).get(ParamKeyConst.BACKUP_TYPE)

    @staticmethod
    def get_sub_job_name(param_dict):
        """获取备份子任务名称"""
        return param_dict.get(ParamKeyConst.SUB_JOB, {}).get(ParamKeyConst.JOB_NAME, "")

    @staticmethod
    def get_sys_auth_type_for_backup(param_dict):
        """获取资源认证类型"""
        return param_dict.get(ParamKeyConst.JOB, {}).get(ParamKeyConst.PROTECT_OBJECT, {})\
            .get(ParamKeyConst.EXT_INFO, {}).get(GstSingleKeyConst.SYS_AUTH_TYPE)

    @staticmethod
    def get_sys_auth_type_for_restore(param_dict):
        """获取资源认证类型"""
        return param_dict.get(ParamKeyConst.JOB, {}).get(ParamKeyConst.TARGET_OBJECT, {})\
            .get(ParamKeyConst.EXT_INFO, {}).get(GstSingleKeyConst.SYS_AUTH_TYPE)

    @staticmethod
    def get_path_from_repositories(repositories: list, repo_type) -> list:
        mount_paths = []
        for repo in repositories:
            tmp_repo_type = repo.get(ParamKeyConst.REPOSITORY_TYPE)
            if tmp_repo_type != repo_type:
                continue
            paths = repo.get(ParamKeyConst.PATH)
            if not paths:
                LOGGER.error(f"The path value in repository is empty, repository type: %s.", tmp_repo_type)
                raise ErrCodeException(ErrorCode.PARAMS_IS_INVALID, message="The path value in repository is empty.")
            mount_paths.append(paths[0])
        if not mount_paths:
            LOGGER.error("The copy mount path list: %s is empty.", mount_paths)
            raise ErrCodeException(ErrorCode.PARAMS_IS_INVALID, message="The copy mount path list is empty。")
        LOGGER.info("Get copy mount path success, paths: %s, repository type: %s.", mount_paths, repo_type)
        return mount_paths

    @staticmethod
    def get_repository_paths_for_backup(param_dict, repo_type) -> list:
        """
        从参数中获取仓库的位置（1: 数据仓；2：cache仓；3：日志仓；4：meta仓）
        """
        repositories = param_dict.get(ParamKeyConst.JOB, {}).get(ParamKeyConst.REPOSITORIES, [])
        return GstSingleParamUtil.get_path_from_repositories(repositories, repo_type)

    @staticmethod
    def get_applications(param_dict):
        """
        获取保护对象信息
        :param param_dict: 任务参数
        :return: 保护对象信息
        """
        return param_dict.get(ParamKeyConst.JOB, {}).get(ParamKeyConst.PROTECT_OBJECT)

    @staticmethod
    def get_sys_auth_type(param_dict):
        """
        获取Application里面的sys的认证类型
        :param param_dict: 任务参数
        :return: 认证类型
        """
        return param_dict.get(ParamKeyConst.APPLICATION, {}).get(ParamKeyConst.EXT_INFO, {}).get(
            GstSingleKeyConst.SYS_AUTH_TYPE)

    @staticmethod
    def get_os_user_name(pid):
        """获取资源的操作系统用户名"""
        os_user_key = GstSingleKeyConst.APP_AUTH_AUTHKEY + "_" + pid
        return get_env_variable(os_user_key)

    @staticmethod
    def get_sys_auth_pwd(pid):
        """获取sys系统用户认证密码"""
        sys_auth_pwd_key = GstSingleKeyConst.APP_SYS_AUTH_PWD + "_" + pid
        return get_env_variable(sys_auth_pwd_key)
